package com.example.func.demos.web;

import com.example.func.dto.request.CreateBranchWithRepoRequest;
import com.example.func.dto.request.MergeBranchRequest;
import com.example.func.dto.request.PullBranchRequest;
import com.example.func.dto.request.RollbackRequest;
import com.example.func.dto.response.ApiResponse;
import com.example.func.dto.response.BranchInfo;
import com.example.func.dto.response.MergeResult;
import com.example.func.service.impl.GitServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Git 管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/git")
public class GitController {
    
    @Autowired
    private GitServiceImpl gitService;
    
    /**
     * 获取分支列表
     */
    @GetMapping("/branches")
    public ApiResponse<List<BranchInfo>> listBranches() {
        List<BranchInfo> branches = gitService.listBranches();
        return ApiResponse.success(branches);
    }
    

    /**
     * 创建分支（指定仓库）
     */
    @PostMapping("/branches/with-repo")
    public ApiResponse<BranchInfo> createBranchWithRepo(@RequestBody CreateBranchWithRepoRequest request) {
        BranchInfo branch = gitService.createBranchWithRepo(request);
        return ApiResponse.success(branch);
    }

    /**
     * 切换分支
     */
    @PostMapping("/branches/checkout")
    public ApiResponse<Void> checkoutBranch(@RequestParam String branchName) {
        gitService.checkoutBranch(branchName);
        return ApiResponse.success(null);
    }
    
    /**
     * 合并分支
     */
    @PostMapping("/merge")
    public ApiResponse<MergeResult> mergeBranch(@RequestBody MergeBranchRequest request) {
        MergeResult result = gitService.mergeBranch(request);
        return ApiResponse.success(result);
    }
    
    /**
     * 检测合并冲突
     */
    @GetMapping("/merge/conflicts")
    public ApiResponse<List<String>> detectConflicts(@RequestParam String sourceBranch,
                                                    @RequestParam String targetBranch) {
        List<String> conflicts = gitService.detectConflicts(sourceBranch, targetBranch);
        return ApiResponse.success(conflicts);
    }
    
    /**
     * 回滚到指定提交
     */
    @PostMapping("/rollback")
    public ApiResponse<Void> rollback(@RequestBody RollbackRequest request) {
        gitService.rollback(request);
        return ApiResponse.success(null);
    }
    
    /**
     * 拉取远程分支到本地并生成测试文件
     */
    @PostMapping("/pull-branch")
    public ApiResponse<String> pullBranchAndCreateTestFile(@RequestBody PullBranchRequest request) {
        String result = gitService.pullBranchAndCreateTestFile(request.getBranchName());
        return ApiResponse.success(result);
    }
}

